<template>
	<view class="content bgGray p16" style="min-height: 100%">
		<form @submit="onSubmit" class="bgWhite flex-r ver-c p16" style="border-radius: 20rpx">
			<view v-for="(item, index) in items" :key="index" class="flex-r mb16">
				<view style="width: 50%" class="flex-r ver-c fs14">
					<view class="gray">奖品{{ index + 1 }}：</view>
					<!-- <input
						type="text"
						class="f1"
						v-model="item.tPrizename"
						placeholder="请输入奖品"
						style="background: #eee; padding: 5rpx"
					/> -->
					<u-input
						class="f1"
						type="text"
						fontSize="12"
						placeholder="请输入奖品"
						v-model="item.tPrizename"
					></u-input>
				</view>
				<view style="width: 50%" class="flex-r ver-c fs14">
					<view class="gray pl16">概率：</view>
					<!-- <input
						class="f1"
						type="digit"
						step="0.01"
						min="0.01"
						placeholder="请输入概率（0.01-100）"
						style="background: #eee; padding: 5rpx"
						max="100"
						v-model.number="item.tProbability"
						@input="updateTotalProbability"
					/> -->
					<u-input
						v-model="item.tProbability"
						type="digit"
						fontSize="12"
						placeholder="请输入概率（0.01-100）"
						@input="(val) => handleInput(val, index)"
						@blur="formatDecimal(index)"
						:formatter="formatter"
					/>
					<text>%</text>
				</view>
			</view>
			<view class="fs13 gray mt16">剩余配置概率：{{ remainingPercentage }}%</view>
			<view class="fs13 red" v-if="totalProbability > 100">错误：总概率已超出100%！</view>
			<view class="fs13 gray">提示：1、中奖概率设置规则，区间0.01-100之间</view>
			<view class="fs13 gray">提示：2、需要满足所有奖品的中奖概率相加等于100</view>
			<view class="flex-r">
				<u-button type="info" customStyle="margin:32rpx 0" @click="addItem" text="添加奖品"></u-button>
				<view style="width: 30rpx"></view>
				<u-button type="info" customStyle="margin:32rpx 0" @click="resetItem" text="重置奖项"></u-button>
			</view>

			<u-button
				type="primary"
				class="mt16"
				:disabled="totalProbability !== 100 || totalProbability > 100"
				@click="onSubmit"
				text="提交"
			></u-button>
		</form>
	</view>
</template>

<script>
import Utils from '@/utils/utils.js'
import { setPrizeRule, getPrizeRule } from '@/api/mine.js'
export default {
	data() {
		return {
			tMerchantid: '',
			items: [{ tPrizename: '', tProbability: null }],
			totalProbability: 0,
			remainingPercentage: 100
		}
	},
	onLoad(option) {
		this.tMerchantid = option.tMerchantid
		this.getPrize(this.tMerchantid)
	},
	methods: {
		// 获取列表
		async getPrize(tMerchantid) {
			try {
				const res = await getPrizeRule(tMerchantid)
				if (res.code == 200 && res.ruleList.length > 0) {
					this.items = res.ruleList.map((rule) => ({
						tPrizename: rule.tPrizename,
						tProbability: parseFloat(rule.tProbability)
					}))
					this.updateTotalProbability()
				}
			} catch (err) {
				console.error(err)
			}
		},
		addItem() {
			this.items.push({ tPrizename: '', tProbability: null })
		},
		resetItem() {
			this.items = [{ tPrizename: '', tProbability: null }]
			this.totalProbability = 0
			this.remainingPercentage = 100
		},
		// 输入时实时校验
		handleInput(val, index) {
			// 1. 过滤非法字符
			let value = val.replace(/[^0-9.]/g, '')

			// 2. 处理多个小数点
			if ((value.match(/\./g) || []).length > 1) {
				value = value.substring(0, value.lastIndexOf('.'))
			}

			// 3. 更新值（保留原始输入用于后续处理）
			this.$set(this.items[index], 'tProbability', value)
		},
		// 失焦时格式化两位小数
		formatDecimal(index) {
			let value = this.items[index].tProbability

			// 1. 空值处理
			if (value === '' || value === '.') {
				this.$set(this.items[index], 'tProbability', '0.00')
				return
			}

			// 2. 分割整数和小数部分
			let [integer = '0', decimal = ''] = value.split('.')

			// 3. 补全两位小数
			decimal = decimal.slice(0, 2).padEnd(2, '0')
			const formatted = `${integer}.${decimal}`

			// 4. 范围校验
			const num = parseFloat(formatted)
			if (num > 100) {
				this.$set(this.items[index], 'tProbability', '0')
			} else if (num < 0.01) {
				this.$set(this.items[index], 'tProbability', '0.01')
			} else {
				this.$set(this.items[index], 'tProbability', formatted)
			}
		},

		// u-input 格式化函数（兼容性处理）
		formatter(value) {
			return value.replace(/[^0-9.]/g, '')
		},
		updateTotalProbability() {
			// 计算总概率
			this.totalProbability = this.items.reduce((acc, item) => {
				const value = Number(item.tProbability) || 0
				return acc + value
			}, 0)

			// 计算剩余概率
			this.remainingPercentage = (100 - this.totalProbability).toFixed(2)

			// 输入时实时验证
			if (this.totalProbability > 100) {
				Utils.toast('总概率不能超过100%')
			}
		},
		async onSubmit(event) {
			if (this.tMerchantid === '') return Utils.toast('登录过期，请重新登录')
			if (this.totalProbability !== 100) return Utils.toast('总概率必须等于100%')

			const data = this.items.map((item) => ({
				...item,
				tMerchantid: this.tMerchantid
			}))

			try {
				const res = await setPrizeRule(data)
				Utils.toast(res.msg)
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			} catch (err) {
				console.error(err)
				Utils.toast('提交失败，请稍后重试')
			}
		}
	},
	watch: {
		items: {
			deep: true,
			handler() {
				this.updateTotalProbability()
			}
		}
	}
}
</script>
